//
// Created by guanyicheng on 2022/3/9.
//

#include "../../common.h"

class Solution {
private:
    int d = 0;
    void swerve() {
        d = (d + 1) % 4;
    }

public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int x = 0, y = 0,  m = matrix.size(), n = matrix[0].size();
        int total = m * n, index = 0;
        vector<int> res(total);
        if (n == 1) {
            d = 1;
        }

        while (index < total) {
            res[index ++] = matrix[x][y];
            cout << x << "," << y << endl;
            if (d == 0) {
                if (++y == n - x - 1) {
                    swerve();
                }
            } else if (d == 1) {
                if (++x == (m - 1) - (n - y - 1)) {
                    swerve();
                }
            } else if (d == 2) {
                if (--y == m - x - 1) {
                    swerve();
                }
            } else if (d == 3) {
                if (--x == y + 1) {
                    swerve();
                }
            }
        }
        return res;
    }
};

int main() {
    vector<vector<int>> matrix = {{1,2,3,4}, {5,6,7,8},{9,10,11,12}};
    auto res = Solution().spiralOrder(matrix);
}